<template>
  <view class="content-page">
    <view :style="{
      height: CustomBarRpx + 'rpx',
      paddingTop: StatusBarRpx + 'rpx',
    }">
      <view :style="{ height: CustomBarRpx + 'rpx' }" class="header-nav">
        <u-icon name="close" @click="close"></u-icon>
      </view>
    </view>
    <view class="login-content">
      <view class="login-content-0">
        <image
          :src="app_logo"
          mode=""></image>
      </view>
      <view class="login-content-1">{{ appName }}</view>
      <!-- #ifdef APP-PLUS -->
      <!-- <view class="login-content-3" @click="onePhoneLogin">{{$t('本机号码一键登录')}}</view> -->
      <!-- #endif  -->
      <!-- #ifdef MP-WEIXIN -->
      <button open-type="getPhoneNumber" @getphonenumber="mpWxLogin" class="login-content-3" v-if="isAgree">
        {{$t('手机号快捷登录')}}
      </button>
      <button class="login-content-3" v-if="!isAgree" @click="mpWxLogin">
        {{$t('手机号快捷登录')}}
      </button>
      <!-- #endif  -->
      <!-- #ifdef H5 -->
      <!-- <view class="login-content-3" @click="gotoPhone">{{$t('验证码登录')}}</view> -->
      <!-- #endif  -->
      <view class="cell-info" style="margin-top: 20rpx" v-if="share_ma">
        <text>{{$t('邀请人为')}}</text>
        {{ share_ma }}
      </view>
      <!-- <view class="login-content-4">{{$t('其它登录方式')}}</view> -->
      <view class="login-content-5">
        <view class="login-content-5-0 tel" @click="gotoPhone">
          <image src="https://img.alicdn.com/imgextra/i1/2215984279448/O1CN01DbjeIF2JfEw5b6udm_!!2215984279448.png"
            mode=""></image>
        </view>
      <!--  <view class="login-content-5-0 wechat" @click="applogin">
          <image src="https://img.alicdn.com/imgextra/i4/2215984279448/O1CN01wQE9Jm2JfEw5b4tbl_!!2215984279448.png"
            mode=""></image>
        </view> -->
		<view class="login-content-5-0 wechat" @click="googlelogin">
		  <image src="../../static/image/google.png"
		    mode=""></image>
		</view>
      </view>
      <!-- #ifdef MP-WEIXIN -->
      <view class="login-content-5" style="justify-content: center">
        <view class="login-content-5-0 tel" @click="gotoPhone">
          <image src="https://img.alicdn.com/imgextra/i1/2215984279448/O1CN01DbjeIF2JfEw5b6udm_!!2215984279448.png"
            mode=""></image>
        </view>
      </view>
      <!-- #endif  -->
    </view>
    <view class="xieyi">
      <span @click="isAgree = !isAgree">
        <u-icon name="checkmark-circle-fill" color="#cccccc" size="34" class="u-icon" v-if="!isAgree"></u-icon>
        <u-icon name="checkmark-circle-fill" color="#2979ff" size="34" class="u-icon" v-if="isAgree"></u-icon>
      </span>
      {{$t('我已阅读并同意')}}<br>
      <text class="book-style" @click="$.to('/pages/my/agreement?type=user_agreement')">《{{$t('用户协议')}}》</text>
      {{$t('和')}}
      <text class="book-style" @click="$.to('/pages/my/agreement?type=privacy_policy')">《{{$t('隐私协议')}}》</text>
    </view>

    <u-popup v-model="showBind" mode="center" :mask-close-able="false">
      <view class="showBind">
        <view class="showBind-0">{{$t('请先绑定手机')}}</view>
        <view class="from-bind">
          <u-field v-model="bindTel" :label="$t('手机号')" :placeholder="$t('请填写手机号')" border type="number"></u-field>
          <u-field v-model="bindTelCode" :label="$t('验证码')" :placeholder="$t('请填写验证码')" border type="number">
            <u-button size="mini" plain slot="right" type="info" @click="getCode">{{ bindCodeText }}</u-button>
          </u-field>
          <u-verification-code ref="uCode" @change="codeChange"></u-verification-code>
        </view>
        <view class="showBind-1">
          <view class="showBind-1-0" @click="bindTelBtn">{{$t('绑定')}}</view>
          <view class="showBind-1-1" @click="cancelTel">{{$t('取消')}}</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import uiConfig from "@/common/ui-config.js";
import {
  iosSdkInfo,
  androidSdkInfo,
  qy_appKey,
  xcx_app_id,
  app_type,
  app_name,
} from "@/utils/keyControl.js";
// #ifdef APP-PLUS
//阿里云短信登录
var aLiSDKModule = uni.requireNativePlugin("AliCloud-NirvanaPns");
//七鱼客服
var qiyuModule = uni.requireNativePlugin("Netease-QiyuModule");
//获取分享安装的邀请码
const sharetrace = uni.requireNativePlugin("shoot-sharetrace");
// #endif
export default {
  data() {
    return {
      StatusBar: null,
      CustomBar: null,
      StatusBarRpx: null,
      CustomBarRpx: null,
      appName: "",
      app_logo: "",
      isAgree: false, // 是否同意协议
      share_ma: "", // 邀请码
      showBind: false,
      bindTel: "", // 绑定手机号
      bindTelCode: "", // 绑定手机号code
      bindCodeText: this.$t('获取验证码'), // 绑定手机号codeText
    };
  },
  onReady() {
    // #ifdef APP-PLUS
    //获取安装的参数;
    sharetrace.getInstallTrace((data) => {
      this.share_ma = data.data.paramsData.split("=")[1] || "";
    });
    // #endif
  },
  onLoad(option) {
	this.getHeight();
    // #ifdef APP-PLUS
    const osName = uni.getSystemInfoSync().osName;
    // 设置一键登录插件&预加载唤起页面
    let secret = "";
    if (osName === "ios") {
      secret = iosSdkInfo;
    } else {
      secret = androidSdkInfo;
    }

    aLiSDKModule.setAuthSDKInfo(secret);
    // 一些检查
    aLiSDKModule.getVersion((version) => {
    });
    aLiSDKModule.checkEnvAvailable(1, (result) => {
    });
    aLiSDKModule.checkEnvAvailable(2, (result) => {
    });
    // 预加载唤起页面
    uni.showLoading({
      title: "Loading",
    });
    aLiSDKModule.accelerateLoginPage(5000, (result) => {
      if (result.resultCode === "600000") {
        uni.hideLoading();
        setTimeout(() => {
          this.oneLogin();
        }, 500);
      } else {
        uni.hideLoading();
        this.$tip.tip( this.$t('一键登录超时，请使用其他方式登录'));
      }
    });
    // #endif
  },
  onShow() { 
	this.getName();
	// #ifdef H5
	this.googleCallBack();
	// #endif
  },
  methods: {
    applogin() {
      if (this.isAgree == false) {
        this.$tip.tip(this.$t("请先同意用户协议和隐私协议"));
        return;
      }
      uni.login({
        provider: "weixin",
        onlyAuthorize: true, // 微信登录仅请求授权认证
        success: (event) => {
          const { code } = event;
          console.log(code, "code________");
          //客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
          this.$http({
            url: "api/login/get_wechat_info_by_app",
            data: {
              code: event.code,
              type: app_type,
            },
          })
            .then((result) => {
              console.log(result, "授权成功");
              if (result.data.code == 1) {
                const mobile = result.data.data.member_data.mobile;
                uni.setStorageSync("user", result.data.data.member_data);
                uni.setStorageSync("user_token", result.data.data.token);
                if (mobile) {
                  uni.switchTab({
                    url: "/pages/tabBar/home",
                  });
                  this.initSetUserInfo(member_data);
                  uni.$emit("updataUser");
                } else {
                  this.showBind = true;
                }
              }
            })
            .catch((err) => {
              console.log(err, "授权失败");
            });
        },
        fail: (err) => {
          this.$tip.tip(this.$t("授权失败"));
          // 登录授权失败
          // err.code是错误码
        },
      });
    },
	// 谷歌登录回调
	googleCallBack() {
		const route = this.$route;
		if (route.query.code) {
			const location = window.location;
			const redirectUrl = location.protocol+"//"+location.host+location.pathname;
			this.$http({
				url: "api/login/google_login",
				data: {
					auth_code: route.query.code,
					redirect_url: redirectUrl
				}
			})
			.then((result) => {
				if (result.data.data.member_data) {
					uni.setStorageSync("user_token", result.data.data.token);
					uni.setStorageSync("user", result.data.data.member_data);
					uni.switchTab({
						url: "/pages/tabBar/home",
					});
					this.initSetUserInfo(result.data.data.member_data);
					uni.$emit("updataUser");
				} else {
					console.log(err, "登录失败");
				}
			})
			.catch((err) => {
				console.log(err, "授权失败");
			});
		}
	},
	// 谷歌登陆
	googlelogin() {
		if (this.isAgree == false) {
			this.$tip.tip(this.$t("请先同意用户协议和隐私协议"));
			return;
		}
		this.$http({
			url: "api/login/google_login",
			data: {
				name: "呼慧杰",
				openid: "109660637147690424717",
				email: "moriatoy@gmail.com",
				device_id: "android"
			}
		})
		.then((result) => {
			if (result.data.data.member_data) {
				uni.setStorageSync("user_token", result.data.data.token);
				uni.setStorageSync("user", result.data.data.member_data);
				uni.switchTab({
					url: "/pages/tabBar/home",
				});
				this.initSetUserInfo(result.data.data.member_data);
				uni.$emit("updataUser");
			} else {
				console.log(err, "登录失败");
			}
		})
		.catch((err) => {
			console.log(err, "授权失败");
		});
		// // #ifdef H5
		// const location = window.location;
		// const redirectUrl = location.protocol+"//"+location.host+location.pathname;
		// this.$http({
		// 	url: "api/login/google_auth_url",
		// 	data: {redirect_url: redirectUrl}
		// })
		// .then((result) => {
		// 	window.location.href = result.data.data.authUrl;
		// })
		// .catch((err) => {
		// 	console.log(err, "授权失败");
		// });
		// // #endif
		// // #ifdef APP-PLUS
		// uni.login({
		// 	provider: 'google',
		// 	success:(loginRes) => {
		// 		uni.getUserInfo({
		// 			provider: 'google',
		// 			success:function(infoRes){
		// 				console.log(infoRes)
		// 			}
		// 		})
		// 	},
		// 	fail: (err) => {
		// 		uni.showToast({
		// 			title: JSON.stringify('网络异常')
		// 		})
		// 	}
		// })
		// // #endif
	},
    close() {
      uni.switchTab({
        url: "/pages/tabBar/home",
      });
    },
    /* 一键登录 */
    initALiSDKModule() { },
    /* 程序 */
    getName() {
      this.$http({
        url: "api/common/get_general",
        })
        .then((res) => {
          if (res.data.code == 1) {
            this.appName = res.data.data.app_name;
            this.app_logo = res.data.data.app_logo;
          }
        })
        .catch((err) => { });
    },

    /* 手机验证码登录 */
    gotoPhone() {
      uni.navigateTo({
        url: "/pagesA/pages/my/loginPhone",
      });
    },
    oneLogin() {
      let _that = this;
      // #ifdef APP-PLUS
      const config = uiConfig.buildFullscreen();
      uni.showLoading();
      aLiSDKModule.getLoginToken(
        12000,
        config,
        async (tokenResult) => {
          uni.hideLoading();
          console.log("一键登录", tokenResult);
          aLiSDKModule.hideLoginLoading();
          if ("600001" == tokenResult.resultCode) {
            console.log("唤起授权页面成功");
          } else if ("600000" == tokenResult.resultCode) {
            // console.log('唤起授权页面成功');
            // this.$tip.tip(tokenResult.token);
            this.$http({
              url: "api/login/getMobile",
              data: {
                token: tokenResult.token,
                share_ma: this.share_ma,
              },
            }).then((res) => {
              const data = res.data;
              if (res.statusCode === 200) {
                aLiSDKModule.quitLoginPage();
                _that.loginNavigate(res.data.data);
              } else {
                LiSDKModule.quitLoginPage();
                uni.showToast({
                  title: this.$t("登录失败"),
                  icon: "error",
                });
              }
            });
          } else {
            uni.hideLoading();
            //其他失败情况，手动关闭授权页
            this.$tip.tip(tokenResult.msg);
            // await toast('登录失败', 'error', tokenResult.msg);
            aLiSDKModule.quitLoginPage();
          }
        },
        (clickResult) => {
          console.log("点击按钮", clickResult);
          switch (clickResult.resultCode) {
            case "700000":
              console.log("用户点击返回按钮");
              break;
            case "700001":
              console.log("用户切换其他登录方式");
              aLiSDKModule.quitLoginPage();
              break;
            case "700002":
              console.log("用户点击登录按钮");
              if (!clickResult.result.isChecked) {
                //Toast样式可参考：https://www.html5plus.org/doc/zh_cn/nativeui.html#plus.nativeUI.toast
                if (!config.uiConfig.setPrivacyAlertIsNeedShow) {
                  plus.nativeUI.toast(this.$t("请同意服务条款"));
                }
              }
              // this.handelLogin()
              break;
            case "700003":
              console.log("用户点击checkBox");
              break;
            case "700004":
              console.log("用户点击协议");
              break;
          }
        }
      );
      // #endif
    },
    onePhoneLogin() {
      // 预加载唤起页面
      uni.showLoading({
        title: "Loading",
      });
      aLiSDKModule.accelerateLoginPage(5000, (result) => {
        if (result.resultCode === "600000") {
          uni.hideLoading();
          setTimeout(() => {
            uni.hideLoading();
            this.oneLogin();
          }, 500);
        } else {
          uni.hideLoading();
          this.$tip.tip(this.$t("一键登录超时，请使用其他方式登录"));
          console.log("预加载一键登录失败", result);
        }
      });
    },
    //获取ip
    getIp() {
		this.$http({
			url: "api/Ios/get_ip",
		})
        .then((res) => {
          if (res.data.code == 1) {
            //res.data.data.ip
            return res.data.data.clear;
          }
        })
        .catch((err) => { });
    },
    /* 初始化七鱼 */
    initSetUserInfo(userInfo) {
      this.testLogout();
      const { id, username, mobile, image, create_time, update_time } =
        userInfo;
      qiyuModule.initSdk({
        appKey: qy_appKey,
        appName: "叮当盲盒",
        pkCerName: "PushKit推送证书名；对应云信的pkCername",
      });
      qiyuModule.setUserInfo(
        {
          userId: id || this.getIp(),
          data: JSON.stringify([
            {
              key: "real_name",
              value: username,
            },
            {
              key: "mobile_phone",
              hidden: true,
              value: mobile,
            },

            {
              key: "avatar",
              value: image,
            },
            {
              index: 5,
              key: "reg_date",
              label: "注册日期",
              value: create_time,
            },
            {
              index: 6,
              key: "last_login",
              label: "上次登录时间",
              value: update_time,
            },
          ]),
        },
        (ret) => { }
      );
    },
    loginNavigate(params) {
      const { mobile, token } = params;
      this.$http({
        url: "api/login/mobile_login",
        data: {
          mobile: mobile,
          token: token,
          share_ma: this.share_ma,
        },
      }).then((res) => {
        if (res.data.code == 1) {
          uni.setStorageSync("user_token", res.data.data.token);
          uni.setStorageSync("user", res.data.data.member_data);
          uni.switchTab({
            url: "/pages/tabBar/home",
          });
          this.initSetUserInfo(res.data.data.member_data);
          uni.$emit("updataUser");
        } else {
          this.$tip.tip(res.data.msg);
        }

        console.log(res, "登录信息");
      });
    },

    getCode() {
      if (this.$refs.uCode.canGetCode) {
        if (!this.bindTel) {
          return this.$u.toast(this.$t("请输入手机号"));
        }
        // 模拟向后端请求验证码
        uni.showLoading({
          title: this.$t("正在获取验证码"),
        });
        this.$http({
          url: "api/login/send_sms",
          data: {
            event: "login",
            mobile: this.bindTel,
          },
        })
          .then((res) => {
            if (res.data.code == 1) {
              uni.hideLoading();
              // 通知验证码组件内部开始倒计时
              this.$refs.uCode.start();
            } else {
              this.$tip.tip(res.data.msg);
            }
          })
          .catch((err) => { });
      } else {
        this.$u.toast(this.$t("倒计时结束后再发送"));
      }
    },
    codeChange(text) {
      // this.bindCodeText = text;
    },

    /* 绑定手机号 */
    bindTelBtn() {
      console.log(
        this.bindTel,
        this.bindTelCode,
        "this.bindTelCodethis.bindTelCodethis.bindTelCode"
      );
      this.$http({
        url: "api/member/bind_mobile",
        data: {
          mobile: this.bindTel,
          code: this.bindTelCode,
        },
      })
        .then((res) => {
          if (res.data.code == 1) {
            let userInfo = uni.getStorageSync("user");
            userInfo.mobile = this.bindTel;
            uni.setStorageSync("user", userInfo);
            this.showBind = false;
            this.$u.toast(this.$t("绑定成功"));
            uni.switchTab({
              url: "/pages/tabBar/home",
            });
            this.initSetUserInfo(userInfo);
            uni.$emit("updataUser");
          } else {
            this.$tip.tip(res.data.msg);
          }
        })
        .catch((err) => { });
    },

    /* wx */
    mpWxLogin(e) {
      if (this.isAgree == false) {
        this.$tip.tip(this.$t("请先同意用户协议和隐私协议"));
        return;
      }
      if (e.detail.encryptedData) {
        let { code, encryptedData, iv } = e.detail;
        this.$http({
          url: "api/login/get_mp_wechat_phone",
          data: {
            code: code,
            //#ifndef MP-WEIXIN
            appid: "",
            // #endif
            //#ifdef MP-WEIXIN
            appid: xcx_app_id,
            // #endif
          },
        })
          .then((result) => {
            if (result.data.code == 1) {
              this.mobile = result.data.data.phoneNumber;
              this.weixin();
            }
          })
          .catch((err) => { });
      } else {
        this.weixin();
        // this.$tip.tip("授权失败")
      }
    },
    weixin() {
      uni.login({
        success: (request) => {
          if (request.code) {
            this.$http({
              url: "api/login/mp_wechat_login",
              data: {
                mobile: this.mobile,
                image: this.app_logo,
                code: request.code,
                share_ma: this.share_ma,
                //#ifndef MP-WEIXIN
                appid: "",
                // #endif
                //#ifdef MP-WEIXIN
                appid: xcx_app_id,
                // #endif
              },
            })
              .then((result) => {
                if (result.data.code == 1) {
                  let user = result.data.data.member_data;
                  // let userToken = result.data.data.token
                  // uni.setStorageSync('user_token', result.data.data.token)
                  uni.setStorageSync("user_token", result.data.data.token);
                  if (user && user.nickname) {
                    uni.setStorageSync("user", user);
                    uni.$emit("updataUser");
                    uni.switchTab({
                      url: "/pages/tabBar/home",
                    });
                    // this.anShow = true
                  } else {
                    this.anShow = true;
                  }
                } else {
                  this.$tip.tip(result.data.msg);
                }
              })
              .catch((err) => { });
          }
        },
      });
    },

    /* 取消绑定 */
    cancelTel() {
      uni.removeStorageSync("user");
      uni.removeStorageSync("user_token");
      uni.$emit("updataUser");
      this.showBind = false;
    },

    /* 获取高度 */
    getHeight() {
      let _that = this;
      uni.getSystemInfo({
        success: function (e) {
			let StatusBar = 0,
				CustomBar = 0,
				CustomVal = 0,
				StatusBarRpx = 0,
				CustomBarRpx = 0,
				unitRatioVal = 0;
			// #ifndef MP
			StatusBar = e.statusBarHeight;
			if (e.platform == "android") {
				CustomBar = e.statusBarHeight + 50;
			} else {
				CustomBar = e.statusBarHeight + 45;
			}
			// #endif
			// #ifdef MP-WEIXIN
			StatusBar = e.statusBarHeight;
			let custom = wx.getMenuButtonBoundingClientRect();
			CustomVal = custom;
			CustomBar = custom.bottom + custom.top - e.statusBarHeight;
			// #endif
			// #ifdef MP-ALIPAY
			StatusBar = e.statusBarHeight;
			CustomBar = e.statusBarHeight + e.titleBarHeight;
			// #endif
			let unitRatio = 750 / uni.getSystemInfoSync().windowWidth;
			StatusBarRpx = StatusBar * unitRatio;
			CustomBarRpx = CustomBar * unitRatio;
			unitRatioVal = unitRatio;
			_that.StatusBar = StatusBar; //状态栏高度(px)
			_that.CustomBar = CustomBar; //整个标题栏高度(px)
			_that.StatusBarRpx = StatusBarRpx; //状态栏高度(rpx)
			_that.CustomBarRpx = CustomBarRpx; //整个标题栏高度(rpx)
			console.log(
				_that.StatusBar,
				_that.CustomBar,
				_that.StatusBarRpx,
				_that.CustomBarRpx
			);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.content-page {
  display: flex;
  flex-direction: column;
  height: 90vh;
  justify-content: space-between;
  background-image: url("http://m-oss.mhbox.top/uploads/20241212/c2bf3ac1604c4cb710acd23f54b173d8.png");
  background-size: 100% 100%;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.login-content {
  width: 750rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;

  // margin-top: 100rpx;
  .login-content-0 {
    width: 300rpx;
    height: 300rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .login-content-1 {
    font-size: 35rpx;
    color: #2c2c2c;
    font-weight: 400;
    margin-top: 20rpx;
  }

  .login-content-2 {
    font-size: 36rpx;
    color: #2c2c2c;
    font-weight: 400;
    margin-top: 70rpx;
    font-weight: bold;
  }

  .login-content-3 {
    width: 600rpx;
    height: 100rpx;
    background-color: #2c2c2c;
    color: #fff;
    opacity: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 80rpx;
  }

  .login-content-4 {
    font-size: 26rpx;
    color: #999;
    margin-top: 100rpx;
  }

  .login-content-5 {
    display: flex;
    width: 380rpx;
    justify-content: space-between;
    margin-top: 50rpx;
    margin-bottom: 20rpx;

    &-0 {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      width: 120rpx;
      height: 120rpx;
      background: #ffffff;
      box-shadow: 0rpx 4rpx 22rpx 0rpx rgba(44, 44, 44, 0.27);
      opacity: 1;
      display: flex;
      justify-content: center;
      align-items: center;

      image {
        width: 50rpx;
        height: 50rpx;
      }
    }
  }
}

.xieyi {
  width: 690rpx;
  font-size: 24rpx;
  margin: 0 auto;
  color: #7b7b7b;
  line-height: 36rpx;
  text-align: center;
  align-items: center;

  .u-icon {
    margin-right: 8rpx;
    position: relative;
    top: 2px;
  }

  .book-style {
    color: #000;
  }
}

.showBind {
  width: 678rpx;
  // height: 390rpx;
  background: #ffffff;
  border-radius: 40rpx 40rpx 40rpx 40rpx;
  opacity: 1;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 40rpx 46rpx;

  .showBind-0 {
    text-align: center;
    height: 60rpx;
    font-size: 36rpx;
    font-weight: bold;
    color: #363636;
    line-height: 60rpx;
  }

  .showBind-1 {
    display: flex;
    justify-content: space-between;
    margin-top: 30rpx;
  }

  .showBind-1-0 {
    width: 264rpx;
    height: 100rpx;
    background: #000;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
    opacity: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #ffffff;
  }

  .showBind-1-1 {
    width: 264rpx;
    height: 100rpx;
    background: #c2c2c2;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
    opacity: 1;
    box-sizing: border-box;
    font-size: 32rpx;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
